package com.kehao.leetcode.hard.array;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class SpiralOrderSolution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        int left=0,up=0,right=matrix[0].length-1,down=matrix.length-1;
        int direction = 0;//0→ 1↓ 2← 3↑
        int i=0,j=0;//位置
        while (left<=right&&up<=down){
            if(direction==0){
                GoRight(result,matrix,i,j,left,right);
                up++;
                j = right;
            }else if(direction ==1){
                GoDown(result,matrix,i,j,up,down);
                right--;
                i = down;
            }else if(direction ==2){
                GoLeft(result,matrix,i,j,left,right);
                down--;
                j = left;
            }else if(direction ==3){
                GoUp(result,matrix,i,j,up,down);
                left++;
                i = up;
            }
            direction= (direction+1)%4;
        }
        return result;
    }

    private void GoUp(List<Integer> result, int[][] matrix, int i, int j, int up, int down) {
        for (int index = down; index >= up; index--) {
            result.add(matrix[index][j]);
        }
    }

    private void GoLeft(List<Integer> result, int[][] matrix, int i, int j, int left, int right) {
        for (int index = right; index >=left; index--) {
            result.add(matrix[i][index]);
        }
    }

    private void GoDown(List<Integer> result, int[][] matrix, int i, int j, int up, int down) {
        for (int index = up; index <=down ; index++) {
            result.add(matrix[index][j]);
        }
    }

    private void GoRight(List<Integer> result, int[][] matrix, int i, int j, int left, int right) {
        for (int index=left;index<=right;index++){
            result.add(matrix[i][index]);
        }
    }

    @Test
    public void test01(){
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        spiralOrder(matrix).stream().forEach(i-> System.out.print(i+" "));
    }

    @Test
    public void test02(){
        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        spiralOrder(matrix).stream().forEach(i-> System.out.print(i+" "));
    }
}
